package com.sale.succ.forms;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.sale.succ.components.DefButton;
import com.sale.succ.components.DefForm;
import com.sale.succ.components.DefInput;
import com.sale.succ.components.DefScrollBarPanel;
import com.sale.succ.components.MessDialog;
import com.sale.succ.datacomp.produce.ProduceListener;
import com.sale.succ.datacomp.produce.ProduceTable;
import com.sale.succ.datacomp.produce.ProduceTableModel;
import com.sale.succ.objects.ProductObj;
import com.sale.succ.objects.Session;
import com.sale.succ.system.TradeMarketException;
import com.sale.succ.system.txt.ObjectsProvider;
import com.sale.succ.system.txt.TXTProcessing;
import com.sale.succ.utils.SystemConstants;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.fx.Insets;
import eve.fx.gui.WindowConstants;
import eve.sys.Event;
import eve.sys.EventListener;
import eve.ui.CellPanel;
import eve.ui.Gui;
import eve.ui.Label;
import eve.ui.event.ControlEvent;

public class ProduceForm extends DefForm implements ProduceListener {
	private ProduceTable produceTable;
	private CellPanel mainPanel;
	private CellPanel topPanel;
	private CellPanel detailPanel;
	private DefInput searchField;
	private DefButton searchButton;

	public ProduceForm() {
		title = TraderHelper.getLabel(TraderConstants.PRODUCE);
		windowFlagsToClear |= WindowConstants.FLAG_HAS_CLOSE_BUTTON;
		addLast(getMainPanel());
		doButtons(OKB | CANCELB);
		// doButtons(CANCELB | OKB);
		windowFlagsToSet |= WindowConstants.FLAG_MAXIMIZE;
		ok.addListener(new EventListener() {
			public void onEvent(Event ev) {
				if (ev.type == ControlEvent.PRESSED) {
					saveOrders();
				}
			}

		});
		cancel.addListener(new EventListener() {
			public void onEvent(Event ev) {
				if (ev.type == ControlEvent.PRESSED) {
					success = true;
				}
			}

		});

	}

	private boolean success = true;

	private void saveOrders() {
		ArrayList orders = ((ProduceTableModel) getProduceTable()
				.getTableModel()).getOrders();
		success = ObjectsProvider.getInstance().saveOrderObjectCollection(
				Session.getInstance().getClientId(), orders, true);
		if (success) {
			modifyRests();
			new MessDialog(TraderHelper.getLabel(TraderConstants.ORDERS_SAVED))
					.execute();
		}
	}
	
	private void modifyRests() {
		HashMap rests = ((ProduceTableModel) getProduceTable().getTableModel())
				.getRests();
		Set keys = rests.keySet();
		Iterator it = keys.iterator();
		while (it.hasNext()) {
			String prodId = (String) it.next();
			ProductObj product = (ProductObj) ObjectsProvider.getInstance()
					.getProductCollection().get(prodId);
			product.setGlobalRest(product.getGlobalRest()
					+ Integer.parseInt(rests.get(prodId).toString()));
		}
		//save rests to file
		ArrayList tempRest = new ArrayList();
		keys = ObjectsProvider.getInstance().getProductCollection().keySet();
		it = keys.iterator();
		while (it.hasNext()) {
			String prodId = (String) it.next();
			ProductObj product = (ProductObj) ObjectsProvider.getInstance().getProductCollection().get(prodId);
			if(product.getGlobalRest() != 0){
				ArrayList temp = new ArrayList();
				temp.add(prodId);
				temp.add(product.getGlobalRest() + "");
				tempRest.add(temp);
			}
		}
		if(tempRest.size() != 0){
			String fileName = SystemConstants.TRADE_ZIP_DIR + File.separator + SystemConstants.RESTS_FILE;
			TXTProcessing.getTXTFromCollection(tempRest, fileName, false);
		}
	}

	private CellPanel getTopPanel() {
		if (topPanel == null) {
			topPanel = new CellPanel();
			topPanel.defaultTags.set(TAG_INSETS, new Insets(0, 0, 0, 0));
			topPanel.addNext(getSearchField());
			topPanel.addNext(getSearchButton());

		}
		return topPanel;
	}

	private Label nameLabel;
	private Label priceLabel;
	private Label restLabel;
	private Label sumLabel;

	private CellPanel getDetailPanel() {
		if (detailPanel == null) {
			Label summTitleLabel = new Label(TraderHelper.getLabel(TraderConstants.SUMM_ORDER) + ":");
			Label nameTitleLabel = new Label(TraderHelper.getLabel(TraderConstants.PRODUCE_NAME));
			Label priceTitleLabel = new Label(TraderHelper.getLabel(TraderConstants.PRODUCE_PRICE));
			Label restTitleLabel = new Label(TraderHelper.getLabel(TraderConstants.PRODUCE_REST));
			
			// nameTitleLabel.setPreferredSize(40, 20);
			// restTitleLabel.setPreferredSize(40, 20);
			sumLabel = new Label("0");
			sumLabel.setPreferredSize(Gui.DESKTOP_WIDTH, 20);
			nameLabel = new Label("");
			nameLabel.setPreferredSize(Gui.DESKTOP_WIDTH, 20);
			restLabel = new Label("");
			restLabel.setPreferredSize(Gui.DESKTOP_WIDTH, 20);

			priceLabel = new Label("");
			priceLabel.setPreferredSize(Gui.DESKTOP_WIDTH, 20);

			detailPanel = new CellPanel();
			detailPanel.defaultTags.set(TAG_INSETS, new Insets(0, 0, 0, 0));

			detailPanel.addNext(summTitleLabel).setCell(HSHRINK);
			detailPanel.addLast(sumLabel);
			detailPanel.addNext(nameTitleLabel).setCell(HSHRINK);
			detailPanel.addLast(nameLabel);
			detailPanel.addNext(restTitleLabel).setCell(HSHRINK);
			detailPanel.addLast(restLabel);
			detailPanel.addNext(priceTitleLabel).setCell(HSHRINK);
			detailPanel.addLast(priceLabel);

			// detailPanel.setMaximumSize(Gui.DESKTOP_WIDTH, 40);

		}
		return detailPanel;
	}

	private DefInput getSearchField() {
		if (searchField == null) {
			searchField = new DefInput();
			searchField.setPreferredSize(50, 20);
		}
		return searchField;
	}

	private DefButton getSearchButton() {
		if (searchButton == null) {
			searchButton = new DefButton(TraderHelper
					.getLabel(TraderConstants.SEARCH));
			searchButton.action = TraderConstants.SEARCH_ACTION;
			searchButton.setPreferredSize(50, 20);
		}
		return searchButton;
	}

	private CellPanel getMainPanel() {
		if (mainPanel == null) {
			mainPanel = new CellPanel();
			DefScrollBarPanel scrollPanel = new DefScrollBarPanel(
					getProduceTable());
			mainPanel.addLast(scrollPanel);
			mainPanel.addLast(getDetailPanel()).setCell(VSHRINK);
		}
		return mainPanel;
	}

	protected boolean canExit(int exitCode) {
		if (success)
			return true;
		return false;
	}

	private ProduceTable getProduceTable() {
		if (produceTable == null) {
			produceTable = new ProduceTable(this);
		}
		return produceTable;
	}

	public boolean handleAction(String action) {

		/*
		 * if (action.equals(TraderConstants.SEARCH_ACTION)) {
		 * getProduceTable().search(getSearchField().getText()); return true; }
		 */

		return super.handleAction(action);
	}

	/**
	 * 0 - name; 1 - rest; 2 - price; 3 - sum;
	 */
	public void applyProduceDetails(ArrayList list, boolean updateSome) {
		try {
			if (updateSome) {
				sumLabel.setText(list.get(3).toString());
			}
			nameLabel.setText(list.get(0).toString());
			restLabel.setText(list.get(1).toString());
			priceLabel.setText(list.get(2).toString());
		} catch (Exception ex) {
			new TradeMarketException(ex.getMessage(),
					"Cannot show produce details");
		}

	}
}
